Page({
  data: {
    userInfo: null,
    isLogin: false,
    playHistory: [],
    recentSongs: [],
    favorites: [],
    userLevel: 1,
    playCount: 0,
    favoriteCount: 0,
    playlistCount: 0,
    downloadCount: 0,
    
    // 展开状态
    showFavoritesSection: false,
    showHistorySection: false,
    showSettings: false,
    
    // 设置选项
    qualityOptions: ['标准', '高品质', '无损'],
    qualityIndex: 1,
    autoPlay: true,
    nightMode: false,
    cacheSize: '0MB'
  },
  
  onLoad() {
    this.checkLoginStatus()
    this.loadUserStats()
    this.calculateCacheSize()
  },
  
  onShow() {
    this.checkLoginStatus()
    this.loadUserStats()
    // 监听全局数据变化
    this.setupGlobalListeners()
  },
  
  onHide() {
    // 页面隐藏时移除监听器
    this.removeGlobalListeners()
  },
  
  setupGlobalListeners() {
    const app = getApp()
    
    // 监听收藏变化
    if (app.globalData.onFavoriteChange) {
      app.globalData.onFavoriteChange = null
    }
    
    app.globalData.onFavoriteChange = () => {
      this.setData({
        favoriteCount: app.globalData.favorites.length
      })
    }
    
    // 监听播放历史变化
    if (app.globalData.onHistoryChange) {
      app.globalData.onHistoryChange = null
    }
    
    app.globalData.onHistoryChange = () => {
      this.setData({
        playHistory: app.globalData.playHistory,
        recentSongs: app.globalData.playHistory
          .sort((a, b) => b.playTime - a.playTime)
          .slice(0, 6)
      })
    }
  },
  
  removeGlobalListeners() {
    const app = getApp()
    app.globalData.onFavoriteChange = null
    app.globalData.onHistoryChange = null
  },
  
  checkLoginStatus() {
    const app = getApp()
    const userInfo = app.globalData.userInfo
    const playHistory = app.globalData.playHistory || []
    const favorites = app.globalData.favorites || []
    
    // 获取最近播放的前6首歌曲
    const recentSongs = playHistory
      .sort((a, b) => b.playTime - a.playTime)
      .slice(0, 6)
    
    this.setData({
      userInfo: userInfo || {},
      isLogin: !!userInfo,
      playHistory: playHistory,
      recentSongs: recentSongs,
      favorites: favorites,
      favoriteCount: favorites.length
    })
  },
  
  loadUserStats() {
    const app = getApp()
    const playHistory = app.globalData.playHistory || []
    const favorites = app.globalData.favorites || []
    const playlists = app.globalData.userPlaylists || []
    
    // 计算播放次数
    const playCount = playHistory.reduce((total, song) => total + (song.playCount || 1), 0)
    
    // 计算用户等级 (基于播放次数)
    const userLevel = Math.floor(playCount / 100) + 1
    
    this.setData({
      playCount: playCount,
      favoriteCount: favorites.length,
      playlistCount: playlists.length,
      downloadCount: 0, // 暂时设为0
      userLevel: Math.min(userLevel, 99) // 最高99级
    })
  },
  
  calculateCacheSize() {
    // 模拟计算缓存大小
    const randomSize = Math.floor(Math.random() * 50) + 10
    this.setData({
      cacheSize: `${randomSize}MB`
    })
  },
  
  goLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },
  
  goSettings() {
    this.setData({
      showSettings: true
    })
  },
  
  hideSettings() {
    this.setData({
      showSettings: false
    })
  },
  
  showFavorites() {
    // 跳转到收藏页面
    wx.navigateTo({
      url: '/pages/favorites/favorites'
    })
  },
  
  hideFavorites() {
    this.setData({
      showFavoritesSection: false
    })
  },
  
  showHistory() {
    // 跳转到播放历史页面
    wx.navigateTo({
      url: '/pages/history/history'
    })
  },
  
  hideHistory() {
    this.setData({
      showHistorySection: false
    })
  },
  
  showAllHistory() {
    // 跳转到播放历史页面
    wx.navigateTo({
      url: '/pages/history/history'
    })
  },
  
  showPlaylists() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },
  
  showDownloads() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },
  
  playSong(e) {
    const song = e.currentTarget.dataset.song
    const app = getApp()
    
    if (song) {
      app.playSong(song)
      app.globalData.currentSong = song
      
      wx.navigateTo({
        url: `/pages/player/player?musicId=${song.id}&name=${encodeURIComponent(song.name)}&artist=${encodeURIComponent(song.artist)}&cover=${encodeURIComponent(song.picUrl || '/assets/default-cover.svg')}&duration=${encodeURIComponent(song.duration || '00:00')}`
      })
    }
  },
  
  removeFavorite(e) {
    e.stopPropagation()
    const songId = e.currentTarget.dataset.id
    const app = getApp()
    
    wx.showModal({
      title: '确认',
      content: '确定要取消收藏这首歌曲吗？',
      success: (res) => {
        if (res.confirm) {
          // 从收藏列表中移除
          const favorites = app.globalData.favorites || []
          const newFavorites = favorites.filter(item => item.id !== songId)
          
          app.globalData.favorites = newFavorites
          
          this.setData({
            favorites: newFavorites,
            favoriteCount: newFavorites.length
          })
          
          wx.showToast({
            title: '已取消收藏',
            icon: 'success'
          })
        }
      }
    })
  },
  
  showSongMenu(e) {
    e.stopPropagation()
    const song = e.currentTarget.dataset.song
    
    wx.showActionSheet({
      itemList: ['添加到歌单', '分享', '删除'],
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            wx.showToast({ title: '功能开发中', icon: 'none' })
            break
          case 1:
            wx.showToast({ title: '功能开发中', icon: 'none' })
            break
          case 2:
            this.removeFavorite({ currentTarget: { dataset: { id: song.id } }, stopPropagation: () => {} })
            break
        }
      }
    })
  },
  
  onQualityChange(e) {
    this.setData({
      qualityIndex: e.detail.value
    })
    
    wx.showToast({
      title: `已切换到${this.data.qualityOptions[e.detail.value]}`,
      icon: 'success'
    })
  },
  
  onAutoPlayChange(e) {
    this.setData({
      autoPlay: e.detail.value
    })
    
    // 保存设置到本地存储
    wx.setStorageSync('autoPlay', e.detail.value)
  },
  
  onNightModeChange(e) {
    this.setData({
      nightMode: e.detail.value
    })
    
    wx.showToast({
      title: e.detail.value ? '已开启夜间模式' : '已关闭夜间模式',
      icon: 'success'
    })
    
    // 保存设置到本地存储
    wx.setStorageSync('nightMode', e.detail.value)
  },
  
  clearCache() {
    wx.showModal({
      title: '清除缓存',
      content: '确定要清除所有缓存数据吗？',
      success: (res) => {
        if (res.confirm) {
          // 模拟清除缓存
          wx.showLoading({ title: '清除中...' })
          
          setTimeout(() => {
            wx.hideLoading()
            this.setData({
              cacheSize: '0MB'
            })
            
            wx.showToast({
              title: '缓存已清除',
              icon: 'success'
            })
          }, 1500)
        }
      }
    })
  },
  
  logout() {
    wx.showModal({
      title: '退出登录',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          const app = getApp()
          
          // 清除用户信息
          app.globalData.userInfo = null
          app.globalData.favorites = []
          
          this.setData({
            userInfo: null,
            isLogin: false,
            favorites: [],
            favoriteCount: 0,
            showSettings: false
          })
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          })
        }
      }
    })
  },
  
  formatTime(timestamp) {
    const date = new Date(timestamp)
    const now = new Date()
    const diff = now - date
    
    // 如果是今天
    if (date.toDateString() === now.toDateString()) {
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `今天 ${hours}:${minutes}`
    }
    
    // 如果是昨天
    const yesterday = new Date(now)
    yesterday.setDate(yesterday.getDate() - 1)
    if (date.toDateString() === yesterday.toDateString()) {
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `昨天 ${hours}:${minutes}`
    }
    
    // 其他日期
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${month}-${day}`
  },
  
  playHistorySong(e) {
    const songId = e.currentTarget.dataset.id
    const app = getApp()
    
    // 查找歌曲
    let song = null
    song = app.globalData.playHistory.find(item => item.id === songId) ||
           app.globalData.favorites.find(item => item.id === songId)
    
    if (song) {
      const fullSong = {
        ...song,
        url: song.url || ''
      }
      
      app.playSong(fullSong)
      app.globalData.currentSong = fullSong
      
      wx.navigateTo({
        url: '/pages/player/player'
      })
    } else {
      wx.showToast({
        title: '无法播放该歌曲',
        icon: 'none'
      })
    }
  }
})